package com.zhengb.nettydemos.chapter3.simple;

import com.zhengb.nettydemos.utils.SerializeUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by zhengbo on 2019/4/2.
 */
public class ClientHandler extends ChannelHandlerAdapter {

    private final static Logger logger = LoggerFactory.getLogger(ClientHandler.class);

    private final ByteBuf sendDataBuf;

    public ClientHandler(DataTransRequestDTO dataTransRequestDTO) {
        byte[] request = SerializeUtil.serialize(dataTransRequestDTO);

        sendDataBuf = Unpooled.buffer(request.length);
        sendDataBuf.writeBytes(request);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(sendDataBuf);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        ByteBuf byteBuf = (ByteBuf) msg;
        byte[] request = new byte[byteBuf.readableBytes()];

        byteBuf.readBytes(request);
        ResponseDTO responseDTO = SerializeUtil.deserialize(request, ResponseDTO.class);
        logger.info("response:{}", responseDTO);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error("{}", cause.getMessage());
        ctx.close();
    }

}
